package purse;

import java.io.IOException;
import java.time.Instant;
import java.util.HashMap;
import java.util.Properties;

import org.json.JSONObject;

import account.Account;
import aimee.apiautotest.HttpRequest;
import aimee.apiautotest.HttpResponse;
import aimee.common.Logger;
import aimee.common.SQLConnection;

/**
 * 实现通宝操作接口
 * 
 * @author 毛建杰
 *
 */
public class GoldProviderImpl implements GoldProvider
{
	private static Properties properties;
	private static String jdbcDriver;

	static
	{
		try
		{
			properties = new Properties();
			properties.load(GoldProviderImpl.class.getResourceAsStream("/purse.properties"));
			jdbcDriver = "com.mysql.cj.jdbc.Driver";
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public int add(Account account, int gold)
	{
		String url = properties.getProperty("mysql.purse.url");
		String user = properties.getProperty("mysql.purse.user");
		String password = properties.getProperty("mysql.purse.password");
		try (SQLConnection sqlConnection = new SQLConnection(jdbcDriver, url, user, password))
		{
			// 充值通宝
			Instant now = Instant.now();
			String bill_no = "MaoJJ" + now.toEpochMilli();
			int mod = account.getUserID() % 16;
			String tableName = String.format("purse_%02d", mod);
			String sql = "insert into " + tableName + " (bill_no,uid,gold,balance,crtime,type,expire) value ('"
					+ bill_no + "'," + account.getUserID() + "," + gold + "," + gold + "," + now.getEpochSecond()
					+ ",1,0)";
			sqlConnection.executeUpdate(sql);
			// 通知余额更新
			HttpRequest httpRequest = new HttpRequest();
			String api = properties.getProperty("api.balance.notify");
			HashMap<String, String> params = new HashMap<>();
			params.put("uid", String.valueOf(account.getUserID()));
			httpRequest.get(api, null, params);
			return query(account);
		}
		catch (Exception e)
		{
			Logger.error(e.getMessage(), e);
			return -1;
		}
	}

	@Override
	public int query(Account account)
	{
		try
		{
			HttpRequest httpRequest = new HttpRequest();
			String api = properties.getProperty("api.purse.query");
			HashMap<String, String> params = new HashMap<>();
			params.put("uid", String.valueOf(account.getUserID()));
			HttpResponse httpResponse = httpRequest.get(api, null, params);
			return new JSONObject(httpResponse.getBody()).getInt(String.valueOf(account.getUserID()));
		}
		catch (Exception e)
		{
			Logger.error(e.getMessage(), e);
			return -1;
		}
	}
}
